package org.jeecg.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.supplier.entity.ProcUserSupplierRelation;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.mapper.ProcUserSupplierRelationMapper;
import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 用户供应商关联表
 * @Author:
 * @Date: 2024-05-29
 * @Version: V1.0
 */
@Service
public class ProcUserSupplierRelationServiceImpl extends ServiceImpl<ProcUserSupplierRelationMapper, ProcUserSupplierRelation> implements IProcUserSupplierRelationService {
    @Autowired
    private ISupplierService supplierService;
    @Override
    public String getUsernameByUserId(String userId) {
        // 重命名为getUsernameBySearchKey，保留此方法以保持兼容性
        ProcUserSupplierRelation relation = getRelationBySearchKey(userId);
        return relation != null && StringUtils.isNotBlank(relation.getUsername()) ? relation.getUsername() : "";
    }

    /**
     * 根据搜索关键字模糊查询关联关系
     * 支持user_id、username、supplier_id的模糊匹配
     * @param searchKey 搜索关键字
     * @return 匹配的关联关系对象，若未找到则返回null
     */
    public ProcUserSupplierRelation getRelationBySearchKey(String searchKey) {
        if (StringUtils.isBlank(searchKey)) {
            return null;
        }
        // 构建查询条件，支持user_id、username、supplier_id的模糊查询
        QueryWrapper<ProcUserSupplierRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_id", searchKey)
                   .or().like("username", searchKey)
                   .or().like("supplier_id", searchKey);

        // 查询第一个匹配的记录并直接返回
        return this.getOne(queryWrapper);
    }
    @Override
    public List<String> getAdminSupplierList() {
        try {
            // 构建查询条件，查询isAdmin等于"1"的记录
            QueryWrapper<ProcUserSupplierRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_admin", "1");

            // 查询符合条件的记录
            List<ProcUserSupplierRelation> relations = this.list(queryWrapper);

            // 提取userId字段并返回
            return relations.stream()
                    .map(ProcUserSupplierRelation::getUserId)
                    .filter(userId -> userId != null && !userId.trim().isEmpty())
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取admin供应商用户列表失败", e);
            return new ArrayList<>();
        }
    }
    @Override
    public boolean setAdminSupplier(String userId) {
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        ProcUserSupplierRelation relation = getRelationBySearchKey(userId);
        if (relation == null) {
            return false;
        }
        relation.setIsAdmin("1");
        return this.updateById(relation);
    }

    @Override
    public List<Supplier> getUnrelatedSuppliers(String companyName) {
        try {
            // 查询所有已关联的供应商ID
            QueryWrapper<ProcUserSupplierRelation> relationWrapper = new QueryWrapper<>();
            relationWrapper.select("DISTINCT supplier_id");
            List<ProcUserSupplierRelation> relations = this.list(relationWrapper);

            // 提取已关联的供应商ID列表
            List<String> relatedSupplierIds = relations.stream()
                    .map(ProcUserSupplierRelation::getSupplierId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 创建供应商查询条件
            QueryWrapper<Supplier> supplierWrapper = new QueryWrapper<>();
            // 添加模糊查询条件,非空则查询companyName
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(companyName)) {
                supplierWrapper.like("company_name", companyName);
            }

            // 查询符合条件的所有供应商
            List<Supplier> allSuppliers = supplierService.list(supplierWrapper);

            // 过滤出未关联的供应商
            List<Supplier> unrelatedSuppliers = allSuppliers.stream()
                    .filter(supplier -> !relatedSupplierIds.contains(supplier.getId()))
                    .collect(Collectors.toList());

            // 如果companyName为空，则返回所有未关联的供应商
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(companyName)) {
                // 查询所有供应商
                List<Supplier> allSuppliersWithoutFilter = supplierService.list();
                // 过滤出未关联的供应商
                unrelatedSuppliers = allSuppliersWithoutFilter.stream()
                        .filter(supplier -> !relatedSupplierIds.contains(supplier.getId()))
                        .collect(Collectors.toList());
            }

            // 返回未关联的供应商列表
            return unrelatedSuppliers;
        } catch (Exception e) {
            // 记录异常信息
            log.error("获取未关联供应商列表失败", e);
            // 返回空列表
            return Collections.emptyList();
        }
    }

}
